/**
 * Created by xaj on 2017/6/6.
 */
var schedule = require('node-schedule');
var fs       = require('fs');
var path     = require('path');
var moment   = require('moment');
var basic    = require('doohanpub').basic;
var process  = require('child_process');

/*每分钟的第30秒触发： '30 * * * * *'
 每小时的1分30秒触发 ：'30 1 * * * *'
 每天的凌晨1点1分30秒触发 ：'30 1 1 * * *'
 每月的1日1点1分30秒触发 ：'30 1 1 1 * *'
 2016年的1月1日1点1分30秒触发 ：'30 1 1 1 1 2016'
 每周1的1点1分30秒触发 ：'30 1 1 * * 1'*/
function BeginCleanLogWork(timeInterval){
    schedule.scheduleJob(timeInterval, cleanLogJob);
}

function BeginCleanPm2LogWork(){
    schedule.scheduleJob('00 00 00 1 * *', cleanPm2LogJob);
}

function BeginCleanImgFileWork() {
    schedule.scheduleJob('00 00 00 * * *', deleteOverDateImg);
}

function cleanLogJob() {
    console.log('[cleanLogJob] BeginDayWork:' + new Date());

    var dateMoment = moment(new Date()).subtract(7, 'days').format('YYYYMMDD')
    let fileName = basic.getLocalIP('eth', 'IPv4') + '-zhengxin-' + dateMoment + '.log';
    let filePath = path.join('./logs/' + fileName);
    console.log(fileName)
    console.log(filePath)

    if (fs.existsSync(filePath)) {
        fs.unlink(filePath, function (err) {
            if (err) {
                console.error('[cleanLogJob] 清除一个月前日志失败，原因：' + JSON.stringify(err));
            }
            else {
                console.log('[cleanLogJob] 清除一个月前日志成功，被清除日志：' + fileName);
            }
        })
    }
    else {
        console.error('[cleanLogJob] 日志文件: %s 不存在', filePath);
    }

}


function cleanPm2LogJob() {
    process.exec('pm2 flush', function (error, stdout, stderr) {
        if (error) {
            console.log('[cleanPm2LogJob] exec error: ' + error);
        }
        else {
            console.log(stdout);
            console.log(stderr);
        }
    });
}
// BeginCleanLogWork();


function deleteOverDateImg() {
    var filePath = path.resolve('./public/images');
    //读取文件目录
    fs.readdir(filePath, function (err, files) {
        if (err) {
            console.log(err);
            return;
        } else {
            console.log('[deleteOverDateImg] images: ', files);
            var reg = /^image+/;
            var j = 0;
            for (let i = 0; i < files.length; i++) {
                if (reg.test(files[i])) {
                    j++;
                    let time = files[i].substring(6, 19);
                    if (time < new Date() - 60*60*1000) {
                        console.log('[deleteOverDateImg] delete image file: ', files[i]);
                        let imageFilePath = path.join('./public/images/' + files[i]);
                        console.log(imageFilePath);
                        fs.unlink(imageFilePath, function (err) {
                            if (err) {
                                console.error('[deleteOverDateImg] 清除一个小时前验证码图片文件失败，原因：' + JSON.stringify(err));
                            }
                            else {
                                console.log('[cleanLogJob] 清除一个小时前验证码图片文件成功，被清除文件：' + imageFilePath);
                            }
                        })
                    }
                }
            }
        }
    })
}


module.exports = {
    "BeginCleanLogWork": BeginCleanLogWork,
    "BeginCleanPm2LogWork": BeginCleanPm2LogWork,
    "cleanLogJob": cleanLogJob,
    "deleteOverDateImg": deleteOverDateImg,
    "BeginCleanImgFileWork": BeginCleanImgFileWork
};
